import Koa from 'koa';
import cors from '@koa/cors';
import bodyParser from 'koa-bodyparser';
import Router from 'koa-router';
import http from 'http';

// 导入模块化路由
import authRoutes from './routes/auth';
import userRoutes from './routes/user';
import merchantRoutes from './routes/merchant';
import productRoutes from './routes/product';
import configRoutes from './routes/config';
import orderRoutes from './routes/order';
import systemRoutes from './routes/system';
import addressRoutes from './routes/user/addresses';
import cartRoutes from './routes/cart';
import uploadRoutes from './routes/upload/avatar';
import ipRoutes from './routes/Amap/ip';
import reviewRoutes from './routes/reviews';
import chatRoutes from './routes/chat';
import aiChatRoutes from './routes/aiChat';
// 管理员后台
import adminDashboardRoutes from './routes/admin/dashboard';
import adminRoutes from './routes/admin';
import adminUserRoutes from './routes/admin/user';
import adminIpRoutes from './routes/admin/ip';
import adminChatRoutes from './routes/admin/chat';
import adminAiChatRoutes from './routes/admin/aiChat';
import adminProductRoutes from './routes/admin/product';
import adminOrderRoutes from './routes/admin/order';
import adminCategoryRoutes from './routes/admin/category';
import categoryRoutes from './routes/category';

// 导入WebSocket服务
import { createWebSocketServer } from './websocket/server';

// 导入数据库测试


const app = new Koa();
const router = new Router();

/// CORS 配置 允许跨越 - 支持SSE流式响应
app.use(cors({
  origin: (ctx) => {
    const origin = ctx.get('Origin');
    const allowedOrigins = [
      // 开发环境
      'http://192.168.11.104:8888',
      'http://192.168.11.104:8080',
      'http://0.0.0.0:8888',
      'http://0.0.0.0:7878',
      'http://192.168.11.104:7878/',
      'http://localhost:3002',
      'http://192.168.11.193:3002',
      'http://192.168.11.194:3002',
     
      // 生产环境 - 主站
      'https://xlcig.cn',
      'https://www.xlcig.cn',
      'http://xlcig.cn',
      'http://www.xlcig.cn',
      'https://admin.xlcig.cn',
      'http://admin.xlcig.cn',
      // 生产环境 - API子域名
      'https://api.xlcig.cn',
      'http://api.xlcig.cn',
      // 备用域名（保留）
      'http://47.94.202.171:8888'
    ];
    console.log('请求来源:', origin);
    return allowedOrigins.includes(origin) ? origin : allowedOrigins[0];
  },
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowHeaders: [
    'Content-Type',
    'Authorization',
    'Accept',
    'Cache-Control',
    'X-Requested-With',
    'Origin',
    'Referer',
    'User-Agent',
    'X-Request-Time'
  ],
  exposeHeaders: ['Content-Type', 'Cache-Control', 'X-Total-Count'],
  credentials: true,
  maxAge: 86400 // 24小时缓存预检结果
}));

// 请求体解析 - 排除multipart请求
app.use(async (ctx, next) => {
  const contentType = ctx.get('content-type') || ''

  // 如果是multipart请求，直接跳过bodyParser
  if (contentType.includes('multipart/')) {
    console.log('跳过bodyParser处理multipart请求:', contentType)
    return next()
  }

  // 其他请求使用bodyParser处理
  return bodyParser({
    enableTypes: ['json', 'form', 'text'],
    extendTypes: {
      text: ['text/xml', 'application/xml']
    },
    formLimit: '50mb',
    jsonLimit: '50mb',
    textLimit: '50mb'
  })(ctx, next)
});

// 健康检查
router.get('/health', (ctx) => {
  ctx.body = {
    success: true,
    message: '服务运行正常',
    timestamp: new Date().toISOString(),
    version: '1.0.0'
  };
});

// 错误处理中间件
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (error: any) {
    console.error('服务器错误:', error);
    ctx.status = error.status || 500;
    ctx.body = {
      success: false,
      message: error.message || '服务器内部错误',
      ...(process.env.NODE_ENV === 'development' && { stack: error.stack })
    };
  }
});

// 注册模块化路由
app.use(authRoutes.routes());     // 认证相关: /api/auth/*
app.use(userRoutes.routes());     // 用户相关: /api/user/*
app.use(merchantRoutes.routes()); // 商家相关: /api/merchants/*
app.use(productRoutes.routes());  // 产品相关: /api/configs/*
app.use(configRoutes.routes());   // 配置相关: /api/config/*
app.use(orderRoutes.routes());    // 订单相关: /api/orders/*
app.use(systemRoutes.routes());   // 系统相关: /api/system/*
app.use(addressRoutes.routes());  // 地址相关: /api/addresses/*
app.use(cartRoutes.routes());     // 购物车相关: /api/cart/*
app.use(uploadRoutes.routes());   // 上传相关: /api/upload/*
app.use(ipRoutes.routes());       // IP定位相关: /api/amap/ip/*
app.use(reviewRoutes.routes());   // 评论相关: /api/reviews/*
app.use(chatRoutes.routes());     // 聊天相关: /api/chat/*
app.use(aiChatRoutes.routes());   // AI聊天相关: /api/aiChat/*
app.use(adminDashboardRoutes.routes()); // 管理员仪表板: /api/admin/dashboard/*
app.use(adminRoutes.routes());    // 管理员后台: /api/admin/*
app.use(adminUserRoutes.routes());    // 管理员后台: /api/admin/users/*用户
app.use(adminIpRoutes.routes());    // 管理员后台: /api/admin/ip/*IP
app.use(adminChatRoutes.routes());    // 管理员后台: /api/admin/chat/*聊天
app.use(adminAiChatRoutes.routes());    // 管理员后台: /api/admin/ai-chat/*AI聊天
app.use(adminProductRoutes.routes());    // 管理员后台: /api/admin/product/*商品管理
app.use(adminOrderRoutes.routes());    // 管理员后台: /api/admin/orders/*订单管理
app.use(adminCategoryRoutes.routes());    // 管理员后台: /api/admin/categories/*类别管理
app.use(categoryRoutes.routes());    // 前端类别接口: /api/categories/*

// 注册基础路由
app.use(router.routes());

// 服务器配置
const PORT = parseInt(process.env.PORT || '9999');
const HOST = '0.0.0.0'; // 监听所有网络接口

// 创建HTTP服务器
const server = http.createServer(app.callback());

// 启用WebSocket
createWebSocketServer(server);

server.listen(PORT, HOST, async () => {
  console.log('🚀 后端服务已启动');
  console.log(`📍 服务地址: http://${HOST}:${PORT}`);
  console.log(`📊 健康检查: http://${HOST}:${PORT}/health`);
  console.log(`🔌 WebSocket服务: ws://${HOST}:${PORT}/websocket`);
  console.log('📝 模块化API架构已启用');
  console.log('');
  console.log('📋 API 模块:');
  console.log('   🔐 认证模块: /api/auth/*');
  console.log('   👤 用户模块: /api/user/*');
  console.log('   🏪 商家模块: /api/merchants/*');
  console.log('   📦 产品模块: /api/configs/*');
  console.log('   ⚙️  配置模块: /api/config/*');
  console.log('   📋 订单模块: /api/orders/*');
  console.log('   🛠️  系统模块: /api/system/*');
  console.log('   📍 地址模块: /api/addresses/*');
  console.log('   🛒 购物车模块: /api/cart/*');
  console.log('   💬 评论模块: /api/reviews/*');
  console.log('   📂 上传模块: /api/upload/*');
  console.log('   🌍 IP定位模块: /api/amap/ip/*');
  console.log('   💬 聊天模块: /api/chat/*');
  console.log('   🤖 AI聊天模块: /api/aiChat/*');
  console.log('   🔧 管理员后台: /api/admin/*');
  console.log('   📦 订单管理: /api/admin/orders/*');
  console.log('   📂 类别管理: /api/categories/*');

  // 测试数据库连接
  try {
    console.log('');
    console.log('🗄️  正在测试数据库连接...');

  } catch (error) {
    console.error('❌ 数据库连接失败:', error);
  }

  console.log('');
  console.log('✅ 服务启动完成');
});


export default app; 